<template>
  <div class="container">
    <header class="header">
      <h1>评委打分系统</h1>
      <div class="logo-text">江苏中烟工业有限责任公司</div>
    </header>

    <main class="main-content">
      <div class="scoring-form">
        <div class="form-group">
          <label for="judgeName">评委姓名：</label>
          <select id="judgeName" v-model="judgeName">
            <option value="">请选择评委</option>
            <option v-for="judge in scoringStore.judges" :key="judge.id" :value="judge.name">
              {{ judge.name }}
            </option>
          </select>
        </div>

        <div class="current-contestant">
          <h3>当前选手信息</h3>
          <div class="contestant-info">
            <template v-if="currentContestant">
              <div class="contestant-details">
                <p><strong>选手编号：</strong>{{ currentContestant.number }}</p>
                <p><strong>选手姓名：</strong>{{ currentContestant.name }}</p>
                <p><strong>状态：</strong><span class="status active">当前评分中</span></p>
              </div>
            </template>
            <template v-else>
              <p>等待管理员激活选手...</p>
            </template>
          </div>
        </div>

        <div class="form-group">
          <label for="score">评分：</label>
          <input type="number" id="score" v-model.number="score" min="0" max="100" step="0.1" placeholder="请输入分数(0-100)" />
        </div>

        <div class="form-group">
          <button class="btn btn-primary" :disabled="!canSubmit" @click="submitScore">提交评分</button>
        </div>

        <div class="message" :class="message.type" v-if="message.text">{{ message.text }}</div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useScoringStore } from '@/stores/scoring'
import { scoreApi } from '@/api'
import type { Contestant } from '@/types'

const scoringStore = useScoringStore()
const currentContestant = ref<Contestant | null>(null)
const judgeName = ref('')
const score = ref<number | null>(null)
const message = ref<{ text: string; type: 'success' | 'error' | 'info' } | { text: ''; type?: any }>({ text: '' })

const canSubmit = computed(() => {
  return (
    !!currentContestant.value &&
    judgeName.value.trim().length > 0 &&
    score.value !== null &&
    !isNaN(score.value) &&
    score.value >= 0 &&
    score.value <= 100
  )
})

function showMessage(text: string, type: 'success' | 'error' | 'info' = 'info') {
  message.value = { text, type }
  setTimeout(() => (message.value = { text: '' }), 3000)
}

async function loadActiveContestant() {
  try {
    // 先刷新选手数据
    await scoringStore.loadContestants()
    currentContestant.value = scoringStore.contestants.find(c => c.is_active) || null
  } catch (e) {
    console.error('加载当前选手失败:', e)
    showMessage('加载当前选手失败', 'error')
  }
}

async function submitScore() {
  if (!currentContestant.value) {
    showMessage('当前没有激活的选手', 'error')
    return
  }
  const name = judgeName.value.trim()
  const value = Number(score.value)
  if (!name) {
    showMessage('请选择评委', 'error')
    return
  }
  if (isNaN(value) || value < 0 || value > 100) {
    showMessage('请输入有效的分数(0-100)', 'error')
    return
  }

  // 只查找已存在的评委，不再自动创建
  const judge = scoringStore.judges.find(j => j.name === name)
  if (!judge) {
    showMessage('评委不存在，请联系管理员添加评委', 'error')
    return
  }

  try {
    const check = await scoreApi.checkJudgeScore(judge.id, currentContestant.value.id)
    if (check.has_scored) {
      showMessage('您已经为这位选手打过分了，不能重复评分', 'error')
      return
    }
  } catch (e) {
    console.warn('检查评分状态失败，继续尝试提交', e)
  }

  try {
    console.log('提交评分数据:', { judge_id: judge.id, contestant_id: currentContestant.value.id, score: value })
    // 直接使用API调用，避免store的复杂逻辑
    const result = await scoreApi.create({ judge_id: judge.id, contestant_id: currentContestant.value.id, score: value })
    console.log('评分提交成功:', result)
    showMessage('评分提交成功！', 'success')
    score.value = null
    // 提交成功后刷新store数据
    await scoringStore.initialize()
  } catch (e: any) {
    console.error('提交评分失败:', e)
    console.error('错误详情:', e.response || e.message)
    showMessage(`提交评分失败: ${e.message || '未知错误'}`, 'error')
  }
}

onMounted(async () => {
  await scoringStore.initialize()
  await loadActiveContestant()
  // 每3秒检查一次当前选手状态和评委列表
  setInterval(async () => {
    await loadActiveContestant()
    await scoringStore.loadJudges()
  }, 3000)
})
</script>

<style scoped>
.scoring-form { max-width: 560px; margin: 0 auto; }
.status.active { color: #28a745; font-weight: bold; }
</style>
